package com.platform.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.platform.dao.FootprintDao;
import com.platform.dao.GoodsAttributeDao;
import com.platform.dao.GoodsDao;
import com.platform.dao.GoodsGalleryDao;
import com.platform.dao.GoodsReadPermissionDao;
import com.platform.dao.ProductDao;
import com.platform.entity.FootprintEntity;
import com.platform.entity.GoodsAttributeEntity;
import com.platform.entity.GoodsEntity;
import com.platform.entity.GoodsGalleryEntity;
import com.platform.entity.GoodsReadPermissionEntity;
import com.platform.entity.ProductEntity;
import com.platform.entity.SysUserEntity;
import com.platform.entity.UserEntity;
import com.platform.utils.RRException;
import com.platform.utils.ShiroUtils;

import jodd.util.StringUtil;

/**
 * Service接口
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-08-21 21:19:49
 */
@Service("goodsService")
public class GoodsService {
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private GoodsAttributeDao goodsAttributeDao;
    @Autowired
    private ProductDao productDao;
    @Autowired
    private GoodsGalleryDao goodsGalleryDao;
	@Autowired
	private FootprintDao footprintDao;
    @Autowired
    private GoodsReadPermissionDao goodsReadPermissionDao;

    @Transactional
    public GoodsEntity queryObject(Integer id) {
    	GoodsEntity goods = goodsDao.queryObject(id);
    	Map<String,Object> params = new HashMap<String,Object>();
    	params.put("goodsId", id);
    	List<GoodsGalleryEntity> goodsImgList = goodsGalleryDao.queryList(params);
    	goods.setGoodsImgList(goodsImgList);
        return goods;
    }

    //    @DataFilter(userAlias = "nideshop_goods.create_user_id", deptAlias = "nideshop_goods.create_user_dept_id")
    public List<GoodsEntity> queryList(Map<String, Object> map) {
        return goodsDao.queryList(map);
    }

    public List<GoodsEntity> queryList(Map<String, Object> map,UserEntity user) {
        return goodsDao.queryList(map);
    }

    public int queryTotal(Map<String, Object> map) {
        return goodsDao.queryTotal(map);
    }

    @Transactional
    public int save(GoodsEntity goods) {
        SysUserEntity user = ShiroUtils.getUserEntity();
        goods.setIsDelete(0);
        goods.setCreateUserDeptId(user.getDeptId());
        goods.setCreateUserId(user.getUserId());
        goods.setUpdateUserId(user.getUserId());
        
        int reuslt = goodsDao.save(goods);
        //保存产品信息
        ProductEntity productEntity = new ProductEntity();
        productEntity.setGoodsId(goods.getId());
        productEntity.setGoodsSn(goods.getGoodsSn());
        productEntity.setGoodsNumber(goods.getGoodsNumber());
        productEntity.setRetailPrice(goods.getRetailPrice());
        productEntity.setMarketPrice(goods.getMarketPrice());
        productEntity.setGoodsSpecificationIds("");
        productDao.save(productEntity);
        
        //商品轮播图
        List<GoodsGalleryEntity> galleryEntityList = goods.getGoodsImgList();
        if (null != galleryEntityList && galleryEntityList.size() > 0) {
            for (GoodsGalleryEntity galleryEntity : galleryEntityList) {
                galleryEntity.setGoodsId(goods.getId());
                goodsGalleryDao.save(galleryEntity);
            }
        }
        return reuslt;
    }

    @Transactional
    public int update(GoodsEntity goods) {
        SysUserEntity user = ShiroUtils.getUserEntity();
        List<GoodsAttributeEntity> attributeEntityList = goods.getAttributeEntityList();
        if (null != attributeEntityList && attributeEntityList.size() > 0) {
            for (GoodsAttributeEntity goodsAttributeEntity : attributeEntityList) {
                int result = goodsAttributeDao.updateByGoodsIdAttributeId(goodsAttributeEntity);
                if (result == 0) {
                    goodsAttributeDao.save(goodsAttributeEntity);
                }
            }
        }
        goods.setUpdateUserId(user.getUserId());
        goods.setUpdateTime(new Date());
        //商品轮播图
        //修改时全删全插
        List<GoodsGalleryEntity> galleryEntityList = goods.getGoodsImgList();
        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("goodsId", goods.getId());
        goodsGalleryDao.deleteByGoodsId(map);

        if (null != galleryEntityList && galleryEntityList.size() > 0) {
            for (GoodsGalleryEntity galleryEntity : galleryEntityList) {
                galleryEntity.setGoodsId(goods.getId());
                goodsGalleryDao.save(galleryEntity);
            }
        }
        return goodsDao.update(goods);
    }

    public int delete(Integer id) {
        SysUserEntity user = ShiroUtils.getUserEntity();
        GoodsEntity goodsEntity = queryObject(id);
        goodsEntity.setIsDelete(1);
        goodsEntity.setIsOnSale(0);
        goodsEntity.setUpdateUserId(user.getUserId());
        goodsEntity.setUpdateTime(new Date());
        return goodsDao.update(goodsEntity);
    }

    @Transactional
    public int deleteBatch(Integer[] ids) {
        int result = 0;
        for (Integer id : ids) {
            result += delete(id);
        }
        return result;
    }

    @Transactional
    public int back(Integer[] ids) {
        SysUserEntity user = ShiroUtils.getUserEntity();
        int result = 0;
        for (Integer id : ids) {
            GoodsEntity goodsEntity = queryObject(id);
            goodsEntity.setIsDelete(0);
            goodsEntity.setIsOnSale(1);
            goodsEntity.setUpdateUserId(user.getUserId());
            goodsEntity.setUpdateTime(new Date());
            result += goodsDao.update(goodsEntity);
        }
        return result;
    }

    public int enSale(Integer id) {
        SysUserEntity user = ShiroUtils.getUserEntity();
        GoodsEntity goodsEntity = queryObject(id);
        if (1 == goodsEntity.getIsOnSale()) {
            throw new RRException("此商品已处于上架状态！");
        }
        goodsEntity.setIsOnSale(1);
        goodsEntity.setUpdateUserId(user.getUserId());
        goodsEntity.setUpdateTime(new Date());
        return goodsDao.update(goodsEntity);
    }

    public int unSale(Integer id) {
        SysUserEntity user = ShiroUtils.getUserEntity();
        GoodsEntity goodsEntity = queryObject(id);
        if (0 == goodsEntity.getIsOnSale()) {
            throw new RRException("此商品已处于下架状态！");
        }
        goodsEntity.setIsOnSale(0);
        goodsEntity.setUpdateUserId(user.getUserId());
        goodsEntity.setUpdateTime(new Date());
        return goodsDao.update(goodsEntity);
    }
    ///////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////     书籍          ///////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////
    public GoodsEntity readArticle(Integer id,UserEntity currentUser) {
	    GoodsEntity goods = goodsDao.queryObject(id);
	    checkReadPermission(goods,currentUser);
		return goods;
    }
    
    public GoodsEntity nextArticle(Integer id,UserEntity currentUser) {
	    GoodsEntity goods = goodsDao.queryObject(id);
	    GoodsEntity nextGoods = goodsDao.nextArticle(goods.getCategoryId(),goods.getSortOrder());
	    if(nextGoods == null) {
	    	return null;
	    }
	    checkReadPermission(nextGoods,currentUser);
		return nextGoods;
    }
    
    public GoodsEntity lastArticle(Integer id,UserEntity currentUser) {
	    GoodsEntity goods = goodsDao.queryObject(id);
	    GoodsEntity lastGoods = goodsDao.lastArticle(goods.getCategoryId(),goods.getSortOrder());
	    if(lastGoods == null) {
	    	return null;
	    }
	    checkReadPermission(lastGoods,currentUser);
		return lastGoods;
    }
    
    private void checkReadPermission(GoodsEntity goods,UserEntity currentUser) {
	    boolean hasReadPermission = false;
	    if(currentUser != null) {
	    	//足迹
			if(goods.getGoodsType() != 99) {   
				footprintDao.noLast(currentUser.getId(),goods.getId());
		    	FootprintEntity footprint = new FootprintEntity();
		    	footprint.setAddTime(new Date());
		    	footprint.setGoodsId(goods.getId());
		    	footprint.setUserId(currentUser.getId().longValue());
		    	footprint.setIsLast(1);
		    	footprintDao.save(footprint);
			}
			//
			if(goods.getUnitPrice().floatValue() > 0) {
				//整书购买
				GoodsReadPermissionEntity goodsReadPermission = goodsReadPermissionDao.existsReadPermission(currentUser.getId(), goods.getCategoryId(), "category");
				if(goodsReadPermission == null) {//全站购买==高级VIP
					goodsReadPermission = goodsReadPermissionDao.existsReadPermission(currentUser.getId(), null, "all");
				}
				if(goodsReadPermission == null) {//单篇购买
					goodsReadPermission = goodsReadPermissionDao.existsReadPermission(currentUser.getId(), goods.getId(), "goods");
				}
				if(goodsReadPermission != null)
					hasReadPermission = true;
			}else {
				hasReadPermission = true;
			}
	    }else {
			if(goods.getUnitPrice().floatValue() <= 0) {
				hasReadPermission = true;
			}
	    }
		goods.setBuyed(hasReadPermission);
    }
}
